package com.ydzt.fanka.server.utils;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class ByteConvert {
	/*
	 * 倒排序卡号
	 * */
	@SuppressWarnings("unused")
	private String getMadStr(String str)
    {
        StringBuilder sb = new StringBuilder();
        char[] strArray = new char[str.length()];
        strArray = str.toCharArray();
        for (int i = str.length() - 1; i > 0; i--)
        {
        	sb.append(strArray[i-1]);
        	sb.append(strArray[i]);
            //sb.append(str.substring(i-1, 1));
            //sb.append(str.substring(i, 1));
            i--;
        }
        String sbStr = sb.toString();
        sb.delete(0, sb.length());
        return sbStr;
    }
	
	public static long dwordBytesToLong(byte[] data) { 
	    return (data[3] << 8 * 3) + (data[2] << 8 * 2) + (data[1] << 8 ) 
	            + data[0]; 
	}
	
	public static byte[] longToDword(long value){ 
	    byte[] data=new byte[4]; 
	    
	    for(int i=0;i<data.length;i++){ 
	        data[i]=(byte) (value>>(8*i)); 
	    } 
	    
	    return data; 
	}
	
	public static byte[] getBytes (char[] chars) {
		   Charset cs = Charset.forName ("UTF-8");
		   CharBuffer cb = CharBuffer.allocate (chars.length);
		   cb.put (chars);
		                 cb.flip ();
		   ByteBuffer bb = cs.encode (cb);
		  
		   return bb.array();
	}
	
	public static String bcd2Str(byte[] bytes) {
        StringBuffer temp = new StringBuffer(bytes.length * 2);  
        for (int i = 0; i < bytes.length; i++) {  
            temp.append((byte) ((bytes[i] & 0xf0) >>> 4));  
            temp.append((byte) (bytes[i] & 0x0f));  
        }  
        /*return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp  
                .toString().substring(1) : temp.toString();*/
        return temp.toString();
    }
	
	/*������"" ���ʾ�����볤�ȴ���*/
	public static String getMsgType(byte[] msgType){
		String high = "";
		String low = "";
		String result = null;
		StringBuilder strBuilder = new StringBuilder();
		byte highByte = 0x00;
		byte lowByte = 0x00;
		if(msgType.length == 2){
			System.arraycopy(msgType, 0, highByte, 0, 1);
			high = ByteConvert.byteToHexString(highByte);
			System.arraycopy(msgType, 1, lowByte, 0, 1);
			low = ByteConvert.byteToHexString(lowByte);
			strBuilder.append(high);
			strBuilder.append(low);
			result = strBuilder.toString();
		}
		else{
			System.out.println("�����볤�ȴ���");
			return "";
		}
		return result;
	}
	
	public static String binaryArrayToIpv4Address(byte[] addr){
		String ip = "";
		for(int i = 0; i < addr.length; i ++){
			ip += (addr[i]& 0xFF) + ".";
		}
		return ip.substring(0, ip.length() - 1);
	}
	
	public static byte[] ipv4Address2BinaryArray(String ipAdd){
		byte[] binIP = new byte[4];
		String[] strs = ipAdd.split("\\.");
		for(int i = 0; i < strs.length;i ++){
			binIP[i] = (byte)Integer.parseInt(strs[i]);
		}
		return binIP;
	}
	
	public static String Convert(String valueType,int length,byte[] value){
		String result = null;
		if(valueType.equals("GB2312") || valueType.equals("STR")){
			result = ByteConvert.byteToString(value).trim();
			return result;
		}
		if(valueType.equals("BCD")){
			result = ByteConvert.byteArrayToHexString(value);
			return result;
		}
		if(valueType.equals("SHORT")){
			try {
				result = String.valueOf(ByteConvert.byteToShort(value));
				return result;
			} catch (DataTranslateException e) {
				e.printStackTrace();
			}
		}
		if(valueType.equals("INT")){
			try {
				result = String.valueOf(ByteConvert.byteToInt(value));
				return result;
			} catch (DataTranslateException e) {
				e.printStackTrace();
			}
		}
		if(valueType.equals("LONG")){
			try {
				result = String.valueOf(ByteConvert.byteToLong(value));
				return result;
			} catch (DataTranslateException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static String byteArrayToHexString(byte[] src){
		StringBuilder stringBuilder = new StringBuilder("");
		for(int i = 0;i < src.length; i ++){
			String tmp = byteToHexString(src[i]);
			stringBuilder.append(tmp);
		}
		String result = stringBuilder.toString();
		return result;
	}
	
	public static String byteToHexString(byte src){  
	    StringBuilder stringBuilder = new StringBuilder("");  
	    int v = src & 0xFF;  
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {  
            stringBuilder.append(0);  
        }
        stringBuilder.append(hv);
	    return stringBuilder.toString();  
	}
	
	/*
	public static int bytesToInt(byte[] intByte) {
		int fromByte = 0;
		for (int i = 0; i < 2; i++){
			int n = (intByte[i] < 0 ? (int)intByte[i] + 256 : (int)intByte[i]) << (8 * i);
			System.out.println(n);
			fromByte += n;
		}
		return fromByte;
    }
	*/
	/**
	* �ֽڵ�shortת��
	* @param b
	* @return
	* @throws DataTranslateException
	*/
	public static short byteToShort(byte[] b) throws DataTranslateException{
	   if(b.length != 2) throw new DataTranslateException();
	   return (short) ((((b[0] & 0xff)<< 8)| b[1] & 0xff));
	}
	
	/**
	* �ֽ����鵽���͵�ת��
	* @param b
	* @return
	* @throws DataTranslateException
	*/
	public static long byteToLong(byte[] b) throws DataTranslateException{
	   if(b.length != 8) throw new DataTranslateException();
	    return ((((long) b[0] & 0xff) << 56) 
	                 | (((long) b[1] & 0xff) << 48) 
	                 | (((long) b[2] & 0xff) << 40) 
	                 | (((long) b[3] & 0xff) << 32) 
	                 | (((long) b[4] & 0xff) << 24) 
	                 | (((long) b[5] & 0xff) << 16) 
	                 | (((long) b[6] & 0xff) << 8) 
	                 | (((long) b[7] & 0xff) << 0)); 
	}
	
	/**
	* �ֽ����鵽doubleת��
	* @param b
	* @return
	* @throws DataTranslateException
	*/
	public static double byteToDouble(byte[] b) throws DataTranslateException{
	   if(b.length != 8) throw new DataTranslateException();
	   long l;
	   l=b[0];
	   l&=0xff;
	   l|=((long)b[1]<<8);
	   l&=0xffff;
	   l|=((long)b[2]<<16);
	   l&=0xffffff;
	   l|=((long)b[3]<<24);
	   l&=0xffffffffl;
	   l|=((long)b[4]<<32);
	   l&=0xffffffffffl;
	  
	   l|=((long)b[5]<<40);
	   l&=0xffffffffffffl;
	   l|=((long)b[6]<<48);
	   l&=0xffffffffffffffl;
	  
	   l|=((long)b[7]<<56);
	  
	   return Double.longBitsToDouble(l);  
	}
	
	/**
	* �ֽ����鵽float��ת��
	* @param b
	* @return
	* @throws DataTranslateException
	*/
	public static float byteToFloat(byte[] b) throws DataTranslateException{
	   if(b.length != 4) throw new DataTranslateException();
	   int l;
	   l=b[0];
	   l&=0xff;
	   l|=((long)b[1]<<8);
	   l&=0xffff;
	   l|=((long)b[2]<<16);
	   l&=0xffffff;
	   l|=((long)b[3]<<24);
	   l&=0xffffffffl;
	   return Float.intBitsToFloat(l);  
	}
	
	/**
	* �ֽ�������ַ��ת��
	* @param b
	* @return
	*/
	public static String byteToString(byte[] b){
	   return new String(b); 
	}
	
	/**
	* �ֽ����鵽����ת��
	* @param b
	* @return
	* @throws DataTranslateException
	*/
	public static int byteToInt(byte[] b) throws DataTranslateException {
	   if(b.length != 4) throw new DataTranslateException();
	        return (int) ((((b[0] & 0xff) << 24) 
	                | ((b[1] & 0xff) << 16) 
	                | ((b[2] & 0xff) << 8)
	                | ((b[3] & 0xff) << 0)));               
	}
	
	public static String byteToAscii(byte[] tBytes){
		String nRcvString = null;
		StringBuffer tStringBuf = new StringBuffer ();
		int tRecvCount = tBytes.length;
		//byte[]tBytes=new byte[]{0x31,0x32,0x33};  //ʵ������ascii���ַ�"123"
		char[] tChars=new char[tRecvCount];
	    for(int i=0;i<tRecvCount;i++){
	    	if(tBytes[i] == 0x00){
	    		tBytes[i] = 0x30;
	    	}
	    	tChars[i]=(char)tBytes[i];
	    }
	    tStringBuf.append(tChars);     
	    nRcvString = tStringBuf.toString();         //nRcvString��tBytesת����String���͵�"123"
	    return nRcvString;
	}
	/*
	 * intתָ�����ȵ�byte[]
	 * */
	public static byte[] toByteArray(int iSource, int iArrayLen) {  
	    byte[] bLocalArr = new byte[iArrayLen];  
	   for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {  
	         bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );  
	  
	    }  
	     return bLocalArr;  
	}  
	
	//����תbyte[] ����Ϊ64
	public static byte[] getBytesByGB(String str,int length){
		byte[] byteGb = new byte[length];
		byte[] tmp = null;
		try {
		    tmp = str.getBytes("GB2312");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for(int i = 0;i < tmp.length; i ++)
		{
			byteGb[i] = tmp[i];
		}
		return byteGb;
	}
	
	/*
	 * longתbyte[]
	 * */
	public static byte[] longToBytes(long n){
		byte[] b = new byte[8];
		b[7] = (byte)(n & 0xff);
		b[6] = (byte)(n >> 8 & 0xff);
		b[5] = (byte)(n >> 16 & 0xff);
		b[4] = (byte)(n >> 24 & 0xff);
		b[3] = (byte)(n >> 32 & 0xff);
		b[2] = (byte)(n >> 40 & 0xff);
		b[1] = (byte)(n >> 48 & 0xff);
		b[0] = (byte)(n >> 56 & 0xff);
		return b;
	}
	
	public static byte[] intToBytes(int n){
		byte[] b = new byte[4];
		b[3] = (byte)(n & 0xff);
		b[2] = (byte)(n >>8 & 0xff);
		b[1] = (byte)(n >> 16 & 0xff);
		b[0] = (byte)(n >> 24 & 0xff);
		return b;
	}
	
	public static byte[] shortToBytes(short n){
		byte[] b = new byte[2];
		b[1] = (byte)(n & 0xff);
		b[0] = (byte)(n >> 8 & 0xff);
		return b;
	}
	
	// ���ַ�ת����һ�����ȵ��ֽ�����  
    /*** 
     * @param  src ��Ҫ���봦���Դ�ַ� 
     * @param  byte_len �̶���С 
     * @return byte[] 
     *    String --> byte[] 
     * **/  
    public  static  byte[] strToBytes(String src,int byte_len){  
        byte[] b1 = new byte[byte_len];  
            StringBuffer tempb = new StringBuffer();     // ��ʱ������  
            int temp_len = 0;                            // ��ʱ�ַ�Ĵ�   
            int src_len = src.length();                  // ��Ҫת�����ַ�ĳ���  
            char zero = '\0';  
            if(src_len<byte_len){  
                temp_len = byte_len - src_len;           // �������λ�Ĵ�С  
                for(int i=0;i<temp_len;i++){             // ѭ�����ռλ��  
                    tempb.append(zero);  
                }   
                b1 = (src+tempb.toString()).getBytes();   
        //      tempb.delete(0, temp_len);               // �����ʱ�ַ�  
            }else{                                       // �����ڴ˹涨�ĳ��ȣ���ֱ��תΪbtye����  
                b1 = src.getBytes();  
            }    
            return b1;  
    }  
    
    //
    public static byte[] str2BcdBlock(String asc) {  
    	if(asc.length() == 0)
    	{
    		asc = "    ";
    	}
        int len = asc.length();  
        int mod = len % 2;  
        if (mod != 0) {  
            asc = "0" + asc;  
            len = asc.length();  
        }  
        byte abt[] = new byte[len];  
        if (len >= 2) {  
            len = len / 2;  
        }  
        byte bbt[] = new byte[len];  
        abt = asc.getBytes();  
        int j, k;  
        for (int p = 0; p < asc.length() / 2; p++) {  
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {  
                j = abt[2 * p] - '0';  
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {  
                j = abt[2 * p] - 'a' + 0x0a;  
            } else {  
                j = abt[2 * p] - 'A' + 0x0a;  
            }  
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {  
                k = abt[2 * p + 1] - '0';  
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {  
                k = abt[2 * p + 1] - 'a' + 0x0a;  
            } else {  
                k = abt[2 * p + 1] - 'A' + 0x0a;  
            }  
            int a = (j << 4) + k;  
            byte b = (byte) a;  
            bbt[p] = b;  
        }  
        
        byte bbresult[] = new byte[len * 2];
        bbresult[0] = bbt[0];
        bbresult[1] = bbt[1];
        bbresult[2] = 0;
        bbresult[3] = 0;
        return bbresult;  
    }  
    
    //8λ
    public static byte[] str2Bcd(String asc) {  
        int len = asc.length();  
        int mod = len % 2;  
        if (mod != 0) {  
            asc = "0" + asc;  
            len = asc.length();  
        }  
        byte abt[] = new byte[len];  
        if (len >= 2) {  
            len = len / 2;  
        }  
        byte bbt[] = new byte[len];  
        abt = asc.getBytes();  
        int j, k;  
        for (int p = 0; p < asc.length() / 2; p++) {  
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {  
                j = abt[2 * p] - '0';  
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {  
                j = abt[2 * p] - 'a' + 0x0a;  
            } else {  
                j = abt[2 * p] - 'A' + 0x0a;  
            }  
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {  
                k = abt[2 * p + 1] - '0';  
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {  
                k = abt[2 * p + 1] - 'a' + 0x0a;  
            } else {  
                k = abt[2 * p + 1] - 'A' + 0x0a;  
            }  
            int a = (j << 4) + k;  
            byte b = (byte) a;  
            bbt[p] = b;  
        }  
       
        return bbt;  
    }
    
    public static String decToHex(String decNumber){
    	long dec = Long.parseLong(decNumber);
    	return Long.toHexString(dec);
    }
    
    public static byte[] str2cbcd(String s) {
    	  if (s.length() % 2 != 0) {
    	   s = "0" + s;
    	  }
    	  ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	  char[] cs = s.toCharArray();
    	  for (int i = 0; i < cs.length; i += 2) {
    	   int high = cs[i] - 48;
    	   int low = cs[i + 1] - 48;
    	   baos.write(high << 4 | low);
    	  }
    	  return baos.toByteArray();
    }
    
    public static byte[] hexStringToBytes(String hexString,int size) {  
        if (hexString == null || hexString.equals("")) {  
            return null;  
        }  
        
        byte tmp[] = new byte[size];
        //��ʼ��Ϊ��
        for(int i = 0;i < size;i++){
        	tmp[i] = 0;
        }
        hexString = hexString.toUpperCase();  
        int length = hexString.length() / 2;  
        char[] hexChars = hexString.toCharArray();  
        byte[] d = new byte[length];  
        for (int i = 0; i < length; i++) {  
            int pos = i * 2;  
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
        }
        
        for(int j = 1;j < length + 1; j ++){
        	tmp[size - j] = d[length - j];
        }
        
        return tmp;
        //return d;  
    }  
    
    private static byte charToByte(char c) {  
        return (byte) "0123456789ABCDEF".indexOf(c);  
    }
    
    /** 
     * @����: 10���ƴ�תΪBCD�� 
     * @����: 10���ƴ� 
     * @���: BCD�� 
     */  
    public static byte[] str2BcdNormal(String asc) {  
        int len = asc.length();  
        int mod = len % 2;  
        if (mod != 0) {  
            asc = "0" + asc;  
            len = asc.length();  
        }  
        byte abt[] = new byte[len];  
        if (len >= 2) {  
            len = len / 2;  
        }  
        byte bbt[] = new byte[len];  
        abt = asc.getBytes();  
        int j, k;  
        for (int p = 0; p < asc.length() / 2; p++) {  
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {  
                j = abt[2 * p] - '0';  
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {  
                j = abt[2 * p] - 'a' + 0x0a;  
            } else {  
                j = abt[2 * p] - 'A' + 0x0a;  
            }  
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {  
                k = abt[2 * p + 1] - '0';  
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {  
                k = abt[2 * p + 1] - 'a' + 0x0a;  
            } else {  
                k = abt[2 * p + 1] - 'A' + 0x0a;  
            }  
            int a = (j << 4) + k;  
            byte b = (byte) a;  
            bbt[p] = b;  
        }  
        return bbt;  
    }  
}
